package com.zengdb.jdbc.handler;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

//把结果集中多条数据封成对象
public class BeanListHandler<T> implements ResultSetHandler<List<T>> {

	private Class<T> clazz;

	//创建类的实例时指定转换具体对象的类
	public BeanListHandler(Class<T> clazz) {
		this.clazz = clazz;
	}

	@Override
	public List<T> handler(ResultSet rs) throws Exception {
		List<T> list = new ArrayList<>();
		//通过内省机制获取类的属性描述
		PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz, Object.class).getPropertyDescriptors();
		while (rs.next()) {
			T obj = clazz.newInstance();
			for (PropertyDescriptor pd : pds) {
				Object value = rs.getObject(pd.getName());
				Method method = pd.getWriteMethod();
				method.invoke(obj, new Object[] { value });
			}
			list.add(obj);
		}
		return list;
	}

}
